package pl.auction_search.views;

import java.net.URL;

import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Layout;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.browser.IWebBrowser;
import org.eclipse.ui.browser.IWorkbenchBrowserSupport;
import org.eclipse.ui.part.DrillDownAdapter;
import org.eclipse.ui.part.ViewPart;

import pl.auction_search.command.ShowResultCommand;
import pl.auction_search.jobs.SearchJob;
import pl.auction_search.model.SearchResultModel;
import pl.auction_search.search.Result;
import pl.auction_search.search.SearchHelper;

/**
 * This sample class demonstrates how to plug-in a new
 * workbench view. The view shows data obtained from the
 * model. The sample creates a dummy model on the fly,
 * but a real implementation would connect to the model
 * available either in this or another plug-in (e.g. the workspace).
 * The view is connected to the model using a content provider.
 * <p>
 * The view uses a label provider to define how model
 * objects should be presented in the view. Each
 * view can present the same model objects using
 * different labels and icons, if needed. Alternatively,
 * a single label provider can be shared between views
 * in order to ensure that objects of the same type are
 * presented in the same way everywhere.
 * <p>
 */
public class AuctionView extends ViewPart {
	private final class SearchKeyListener extends KeyAdapter {
		@Override public void keyReleased(KeyEvent keyevent) {
			if (keyevent.character == '\n' || keyevent.character == '\r') {
				goSearch();
			}
		}

		private void goSearch() {
			final String query = searchField.getText();
			final Job job = new SearchJob(query, new ShowResultCommand(searchResultModel) {
				private static final long serialVersionUID = 1;

				public void refreshView() {
					Display.getDefault().asyncExec(new Runnable() {
						public void run() {
							viewer.refresh();
						}
					});
				}
			});
			job.setPriority(Job.SHORT);
			job.schedule();
		}
	}

	/**
	 * The ID of the view as specified by the extension.
	 */
	public static final String ID = "pl.auction_search.views.AuctionView";

	private TreeViewer viewer;
	private DrillDownAdapter drillDownAdapter;
	private Action showPropertiesAction;
	private Action doubleClickAction;

	private Text searchField;
	protected SearchResultModel searchResultModel = new SearchResultModel();

	/**
	 * The constructor.
	 */
	public AuctionView() {}

	/**
	 * This is a callback that will allow us
	 * to create the viewer and initialize it.
	 */
	public void createPartControl(Composite parent) {
		parent.setLayout(createLayout());

		searchField = new Text(parent, SWT.BORDER);
		searchField.setLayoutData(new GridData(GridData.FILL, GridData.BEGINNING, false, false));
		searchField.setToolTipText("fype filter text");
		searchField.addKeyListener(new SearchKeyListener());

		viewer = new TreeViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER);
		drillDownAdapter = new DrillDownAdapter(viewer);

		viewer.setContentProvider(new ViewContentProvider(this, searchResultModel));
		viewer.setLabelProvider(new ViewLabelProvider());
		viewer.setSorter(new NameSorter());

		// selection provider
		getSite().setSelectionProvider(viewer);
		viewer.setInput(getViewSite());

		viewer.getTree().setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, true));

		// Create the help context id for the viewer's control
		PlatformUI.getWorkbench().getHelpSystem().setHelp(viewer.getControl(), "pl.search.auctions.ui.viewer");

		makeActions();
		hookContextMenu();
		hookDoubleClickAction();
		contributeToActionBars();
	}

	private Layout createLayout() {
		GridLayout layout = new GridLayout();
		layout.numColumns = 1;
		return layout;
	}

	private void hookContextMenu() {
		MenuManager menuMgr = new MenuManager("#PopupMenu");
		menuMgr.setRemoveAllWhenShown(true);
		menuMgr.addMenuListener(new IMenuListener() {
			public void menuAboutToShow(IMenuManager manager) {
				AuctionView.this.fillContextMenu(manager);
			}
		});
		Menu menu = menuMgr.createContextMenu(viewer.getControl());
		viewer.getControl().setMenu(menu);
		getSite().registerContextMenu(menuMgr, viewer);
	}

	private void contributeToActionBars() {
		IActionBars bars = getViewSite().getActionBars();
		fillLocalPullDown(bars.getMenuManager());
		fillLocalToolBar(bars.getToolBarManager());
	}

	private void fillLocalPullDown(IMenuManager manager) {
		manager.add(showPropertiesAction);
	}

	private void fillContextMenu(IMenuManager manager) {
		manager.add(showPropertiesAction);
		drillDownAdapter.addNavigationActions(manager);
		// Other plug-ins can contribute there actions here
		manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
	}

	private void fillLocalToolBar(IToolBarManager manager) {
		manager.add(showPropertiesAction);
		drillDownAdapter.addNavigationActions(manager);
	}

	private void makeActions() {
		showPropertiesAction = new Action() {
			public void run() {
				IWorkbenchPage activePage = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
				try {
					activePage.showView("org.eclipse.ui.views.PropertySheet");
				} catch (PartInitException e) {
					e.printStackTrace();
				}
			}
		};
		showPropertiesAction.setText("Show Properties");
		showPropertiesAction.setToolTipText("Show Properties");
		showPropertiesAction.setImageDescriptor(PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(
				ISharedImages.IMG_OBJS_INFO_TSK));

		doubleClickAction = new Action() {
			public void run() {
				ISelection selection = viewer.getSelection();
				Object obj = ((IStructuredSelection) selection).getFirstElement();
				
				try {
					if(obj instanceof Result){
						Result result = (Result)obj;
						URL url = new URL(result.getUrl());	

						IWorkbenchBrowserSupport browserSupport = PlatformUI.getWorkbench().getBrowserSupport();
						IWebBrowser browser = browserSupport.createBrowser(IWorkbenchBrowserSupport.LOCATION_BAR
								| IWorkbenchBrowserSupport.NAVIGATION_BAR, "browserId", result.getName(), result.getCategory());
						browser.openURL(url);
					}
				} catch (Exception ex) {
					SearchHelper.handleException(ex);
				}
			}
		};
	}

	private void hookDoubleClickAction() {
		viewer.addDoubleClickListener(new IDoubleClickListener() {
			public void doubleClick(DoubleClickEvent event) {
				doubleClickAction.run();
			}
		});
	}

//	private void showMessage(String message) {
//		MessageDialog.openInformation(viewer.getControl().getShell(), "AuctionView", message);
//	}

	/**
	 * Passing the focus request to the viewer's control.
	 */
	public void setFocus() {
		viewer.getControl().setFocus();
	}
}